<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Roles extends Admin_Controller {

	public $model = "roles";
	public $view = "roles";
	public $permissionCreate = 'Roles.Create';
    public $permissionDelete = 'Roles.Delete';
    public $permissionEdit   = 'Roles.Edit';
    public $permissionView   = 'Roles.View';
	
	protected $index_show = array(
		array( 'field' => 'role_id',
				'label' => 'role id'),	
		array( 'field' => 'role_name',
				'label' => 'role name',
				'custom_value' => '<a href="{url_edit}{role_id}">{role_name}</a>', //replace value
				),
		array( 'field' => 'role_description',
				'label' => 'role description'),
	);
    function __construct() {
        parent::__construct();
        $this->load->model($this->model.'_m',$this->model);
    }
	

	function permissions($role_id = 0)
	{
		$this->load->model('role_permission_m');
		$this->load->model('permission_m','permission');
		if($role_id <=0)
		{
			$this->messages->add('Mã nhóm không tồn tại','error');
			redirect(admin_url(), 'location');
		}
		$this->load->model('group_permissions_m');
		$data = array();
		$groups = array();
		if($permissions = $this->input->post('per_id'))
		{
			$arr_insert = array();
			if($permissions)
			foreach($permissions as $id => $permission)
			{
				if($permission =='on')
				{
					$arr_insert[] = array(
						'role_id'=>$role_id,
						'permission_id'=>$id
					);
				}
			}
			if(count($arr_insert) >0)
			{
				$this->role_permission_m->delete_many_by('role_id',$role_id);
				
				$this->role_permission_m->insert_many($arr_insert);
				$this->messages->add("OK", "success");
			}
		}
		 
		
		$permissions = $this->permission->get_many_by();
		
		$this->group_permissions_m->order_by('pgroup_order');
		$data['groups'] = $this->group_permissions_m->get_many_by();
		foreach($permissions as $permission)
		{
			$role = explode('.',$permission->permission_name);
			$arr_role_name = count($role)-1;
			
			$role_action = array_pop($role);
			$role_name = implode('.',$role);
			if(!$role_action ) continue;
			$data['permissions'][$permission->pgroup_id][$role_name][$role_action] = $permission;
			$data['permission_tab'][$permission->pgroup_id][$role_action] = $role_action;
			
		}
		
		$data['role_id'] =$role_id; 
		$this->theme_data["main"] = $this->view."/permissions";
        $this->template->viewAdmin($this->theme_data, $data);
	}
}
